package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.enums.AuditManagerEnum;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.listener.easyexcel.AuditImportListener;
import com.settlement.system.mapper.security.userdetails.SysUserDetails;
import com.settlement.system.model.entity.SysAudit;
import com.settlement.system.model.entity.SysFileAudit;
import com.settlement.system.model.query.AuditPageQuery;
import com.settlement.system.model.query.BillPageQuery;
import com.settlement.system.model.query.HistoryAuditQuery;
import com.settlement.system.model.vo.AuditVo;
import com.settlement.system.model.vo.SysAuditExportVO;
import com.settlement.system.service.SysAuditService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <p>
 * 标准核销表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-05
 */
@Tag(name = "标准核销表")
@RestController
@RequestMapping("/api/v1/audit")
@RequiredArgsConstructor
public class SysAuditController {

    private final Logger logger = LoggerFactory.getLogger(SysAuditController.class);

    public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(4);

    private final SysAuditService auditService;

    @Operation(summary = "标准核销单分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysAudit> getAuditPage(@ParameterObject AuditPageQuery queryParams) {
        Page<SysAudit> result = auditService.getAuditPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "所有核销单分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/pageAll")
    public PageResult<SysAudit> pageAll(@ParameterObject AuditPageQuery queryParams) {
        Page<SysAudit> result = auditService.pageAll(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "获取详情", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping(value = "/{auditId}")
    public Result<AuditVo> getAuditForm(@Parameter(description = "核销单ID") @PathVariable String auditId) {
        AuditVo formData = auditService.getAuditForm(auditId);
        return Result.success(formData);
    }

    @Operation(summary = "获取标准订单详情", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping(value = "/order/{linkNo}")
    public Result<?> getOrderList(@Parameter(description = "关联单号") @PathVariable String linkNo) {
        return Result.success(auditService.getOrderList(linkNo));
    }

    @Operation(summary = "获取标准订单明细详情", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping(value = "/orderDetail/{linkNo}")
    public Result<?> getOrderDetailList(@Parameter(description = "关联单号") @PathVariable String linkNo) {
        return Result.success(auditService.getOrderDetailList(linkNo));
    }

    @Operation(summary = "获取标准账单详情", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping(value = "/bill/{linkNo}")
    public Result<?> getBillDetail(@Parameter(description = "关联单号") @PathVariable String linkNo) {
        return Result.success(auditService.getBillDetail(linkNo));
    }

    @Operation(summary = "获取历史关联核销单", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping(value = "/auditList")
    public Result<?> auditList(@RequestBody List<HistoryAuditQuery> historyAuditQueryList) {
        List<SysFileAudit> fileAudits = auditService.auditList(historyAuditQueryList);
        return Result.success(fileAudits);
    }

    @Operation(summary = "导出核销单（勾选后导出）", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_export")
    public void exportAudits(@RequestBody BillPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "核销单-%s.xlsx".formatted(DateUtils.getDateString());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysAuditExportVO> exportVOList = auditService.listExportAudits(queryParams.getIds());
        EasyExcel.write(response.getOutputStream(), SysAuditExportVO.class).sheet("核销单").doWrite(exportVOList);
    }

    @Operation(summary = "导出核销单（搜索后导出）", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    public void exportUsers(AuditPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "核销单-%s.xlsx".formatted(DateUtils.getDateString());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        queryParams.setPageNum(1);
        queryParams.setPageSize(300);
        Page<SysAudit> auditPage = auditService.getAuditPage(queryParams);
        long totalPage = auditPage.getPages();
        logger.info("每页300条，一共查询到{}页...", totalPage);
        List<Future<List<SysAuditExportVO>>> futureList = new ArrayList<>();
        SysUserDetails userDetails = SecurityUtils.getUser();
        for (int i = 1; i <= totalPage; i++) {
            AuditPageQuery query = new AuditPageQuery();
            BeanUtils.copyProperties(queryParams, query);
            query.setPageNum(i);
            query.setPageSize(300);
            query.setManager(AuditManagerEnum.YES.getValue().equals(userDetails.getManager()));
            Future<List<SysAuditExportVO>> submit = EXECUTOR_SERVICE.submit(() -> auditService.queryByPage(query));
            logger.info("正在查询第{}页，添加到线程池中...", i);
            futureList.add(submit);
        }
        logger.info("正在写入表格...");
        try (ExcelWriter writer = EasyExcel.write(response.getOutputStream(), SysAuditExportVO.class).build()) {
            WriteSheet sheet = EasyExcel.writerSheet("核销单").build();
            // 循环写入数据
            for (Future<List<SysAuditExportVO>> future : futureList) {
                try {
                    logger.info("正在处理线程的数据...");
                    List<SysAuditExportVO> exportVOList = future.get();
                    writer.write(exportVOList, sheet);
                    // 释放内存
                    exportVOList.clear();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("写入表格完成...");
    }

    @Operation(summary = "导入核销单", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    public Result<?> importAudits(MultipartFile file) throws IOException {
        AuditImportListener listener = new AuditImportListener();
        EasyExcelFactory.read(file.getInputStream(), SysAuditExportVO.class, listener).sheet(0).doRead();
        List<SysAuditExportVO> vos = listener.getVos();
        // 导入的财务调账金额数据覆盖更新系统核销单原有数据
        return Result.success(auditService.reload(vos));
    }

    @Operation(summary = "重新执行36条规则", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping(value = "/reBill")
    public Result<?> reBill(@RequestBody BillPageQuery queryParams) {
        auditService.reBill(queryParams.getIds());
        return Result.success();
    }


}
